package pikes.ecma;

import java.io.IOException;
import java.io.StringWriter;

public abstract class PrintableSourceElement implements SourceElement {

	public static PrintableSourceElement NO_SOURCE = new PrintableSourceElement() {

		public void visit(SyntaxTreeVisitor syntaxTreeVisitor) throws EcmaSyntaxVisitingException {

		}

	};

	/**
	 * Calls visit method with XMLWriter as parameter.
	 * @param appendable character stream
	 * @throws IOException
	 */
	final public void print(Appendable appendable) throws IOException {
		FormattingScriptPrinter xmlWriter = new FormattingScriptPrinter(appendable);
		try {
			visit(xmlWriter);
		}
		catch (Exception e) {
			throw new IOException(e.getMessage());
		}
	}

	/**
	 * Calls print method with StringWriter as parameter. If an exception is thrown, empty string is returned.
	 */
	@Override
	public String toString() {
		StringWriter writer = new StringWriter();
		try {
			print(writer);
		}
		catch (Exception e) {
			return "";
		}
		writer.flush();
		return writer.toString();
	}

}
